package creator;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;


public class XmlReader {	
	public XmlReader(String file) {
		this.file = file;
		objects = new ArrayList<ObjectInfo>();
	}
	
	public void lookupStart() {
		List<Element> childList;
		SAXReader saxReader = new SAXReader();
		Document document = null;
		try {
			document = saxReader.read(new File(file));
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		// 获取根元素<classes>
		Element root = document.getRootElement();
		
		// 获取根节点下的所有子节点
		childList = root.elements();
		lookupObjects(childList);
	}
	
	private void lookupObjects(List<Element> elements) {
		for (Element e: elements) {
			String objectName = e.getName();
			String packageName = e.attributeValue("package");			
			String extendsObject = e.attributeValue("extends");		// maybe null
			
			ObjectInfo objectInfo = new ObjectInfo();
			objectInfo.setName(objectName);
			objectInfo.setPackageName(packageName);
			objectInfo.setExtendsObject(extendsObject);
			
			lookupProperties(e, objectInfo);
			objects.add(objectInfo);
		}
	}
	
	private void lookupProperties(Element element, ObjectInfo objectInfo) {
		List<String> imports = new ArrayList<String>();
		List<Property> properties = new ArrayList<Property>();
		List<Element> childList = element.elements();
		for (Element e: childList) {
			String node = e.getName();
			if (node.equals("import")) {
				imports.add(e.getText());
			} else {
				String type = e.attributeValue("type");
				String comment = e.attributeValue("comment");				
				properties.add(new Property(node, type, comment));
			}
		}
		
		objectInfo.setImports(imports);
		objectInfo.setProperties(properties);
	}
	
	public List<ObjectInfo> getObjects() {
		return objects;
	}

	private String file;
	private List<ObjectInfo> objects;
}
